package com.bfly.core.config;

import com.bfly.common.ResponseUtil;
import com.bfly.core.base.entity.ResponseData;
import com.bfly.core.enums.SysError;
import com.bfly.core.exception.ServiceResponseException;
import com.bfly.core.exception.UnLoginException;
import com.octo.captcha.service.CaptchaServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理
 *
 * @author 长沙商脉科技有限公司
 * @date 2019/8/19 11:19
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 404处理
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/11/12 16:25
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public void notFountHandler(HttpServletResponse response, HttpServletRequest request, NoHandlerFoundException e) {
        String method = request.getMethod();
        String path = request.getRequestURI();
        Map<String, Object> data = new HashMap<>();
        data.put("method", method);
        data.put("path", path);
        ResponseUtil.writeJson(response, ResponseData.getFail(SysError.NOT_FOUND, data));
    }

    @ExceptionHandler
    public void exceptionHandler(HttpServletResponse response, Exception ex) {
        doAjax(response, ex);
    }

    /**
     * Ajax请求处理
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/7/26 16:13
     */
    private void doAjax(HttpServletResponse response, Exception ex) {
        boolean log = true;
        SysError error = SysError.ERROR;
        if (ex instanceof ServiceResponseException) {
            int code = ((ServiceResponseException) ex).getCode();
            error = SysError.get(code);
            error.setMessage(ex.getMessage());
        } else if (ex instanceof CaptchaServiceException) {
            error.setMessage("验证码已失效!");
        } else if (ex instanceof NullPointerException) {
            error.setMessage("数据为空!");
        } else if (ex instanceof UnLoginException) {
            error.setMessage(ex.getMessage());
            error = SysError.UNAUTHORIZED;
            log = false;
        } else {
            error.setMessage(ex.getMessage());
        }
        if (log) {
            logger.error("请求异常", ex);
        }
        ResponseUtil.writeJson(response, ResponseData.getFail(error, error.getMessage()));
    }
}